package com.industrial.app.controller;

import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateUtil;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.industrial.app.domain.BizFocusSchedulingProductProduction;
import com.industrial.app.domain.request.BizFocusSchedulingProductProductionRequest;
import com.industrial.app.service.IBizFocusSchedulingProductProductionService;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.controller.BaseController;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.core.web.page.TableDataInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * 重点调度产品产量Controller
 *
 * @author SangGuangCan
 * @date 2023-12-29
 */
@RestController
@RequestMapping("/biz/production")
public class BizFocusSchedulingProductProductionController extends BaseController
{
    private IBizFocusSchedulingProductProductionService bizFocusSchedulingProductProductionService;

    @Value("${app.file-upload-path}")
    private String fileUploadPath;

    @Autowired
    public BizFocusSchedulingProductProductionController(IBizFocusSchedulingProductProductionService bizFocusSchedulingProductProductionService){
        this.bizFocusSchedulingProductProductionService = bizFocusSchedulingProductProductionService;
    }

    /**
     * 查询重点调度产品产量列表
     */
//    @PreAuthorize("@ss.hasPermi('biz:production:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizFocusSchedulingProductProduction bizFocusSchedulingProductProduction)
    {
        startPage();
        List<BizFocusSchedulingProductProduction> list = bizFocusSchedulingProductProductionService.selectBizFocusSchedulingProductProductionList(bizFocusSchedulingProductProduction);
        return getDataTable(list);
    }

    /**
     * 导出重点调度产品产量列表
     */
//    @PreAuthorize("@ss.hasPermi('biz:production:export')")
//    @Log(title = "重点调度产品产量", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizFocusSchedulingProductProduction bizFocusSchedulingProductProduction)
    {
        List<BizFocusSchedulingProductProduction> list = bizFocusSchedulingProductProductionService.selectBizFocusSchedulingProductProductionList(bizFocusSchedulingProductProduction);
        ExcelUtil<BizFocusSchedulingProductProduction> util = new ExcelUtil<BizFocusSchedulingProductProduction>(BizFocusSchedulingProductProduction.class);
        util.exportExcel(response, list, "重点调度产品产量数据");
    }

    /**
     * 获取重点调度产品产量详细信息
     */
//    @PreAuthorize("@ss.hasPermi('biz:production:query')")
    @GetMapping(value = "/{baseId}")
    public AjaxResult getInfo(@PathVariable("baseId") String baseId)
    {
        return success(bizFocusSchedulingProductProductionService.selectBizFocusSchedulingProductProductionByBaseId(baseId));
    }

    /**
     * 新增重点调度产品产量
     */
//    @PreAuthorize("@ss.hasPermi('biz:production:add')")
//    @Log(title = "重点调度产品产量", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizFocusSchedulingProductProduction bizFocusSchedulingProductProduction)
    {
        try{
            return toAjax(bizFocusSchedulingProductProductionService.insertBizFocusSchedulingProductProduction(bizFocusSchedulingProductProduction));
        }catch (DuplicateKeyException e){
            return AjaxResult.warn("该产品对应年月已经录入完成,完须重复录入");
        }catch (Exception e){
            return AjaxResult.error("未知错误");
        }
    }

    /**
     * 修改重点调度产品产量
     */
//    @PreAuthorize("@ss.hasPermi('biz:production:edit')")
//    @Log(title = "重点调度产品产量", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizFocusSchedulingProductProduction bizFocusSchedulingProductProduction)
    {
        return toAjax(bizFocusSchedulingProductProductionService.updateBizFocusSchedulingProductProduction(bizFocusSchedulingProductProduction));
    }

    /**
     * 删除重点调度产品产量
     */
//    @PreAuthorize("@ss.hasPermi('biz:production:remove')")
//    @Log(title = "重点调度产品产量", businessType = BusinessType.DELETE)
    @DeleteMapping("/{baseIds}")
    public AjaxResult remove(@PathVariable String[] baseIds)
    {
        return toAjax(bizFocusSchedulingProductProductionService.deleteBizFocusSchedulingProductProductionByBaseIds(baseIds));
    }

    @GetMapping("/getAppTableData")
    public AjaxResult getAppTableData(BizFocusSchedulingProductProductionRequest request){
        try{
            String dates = request.getDates();
            if(StringUtils.isBlank(dates)){
                return AjaxResult.warn("没有找到日期");
            }
            DateUtil.parse(request.getDates(),"yyyy年MM月");
            return AjaxResult.success(this.bizFocusSchedulingProductProductionService.getAppTableData(request));
        }catch (DateException de){
            logger.error("日期格式校验失败,传入日期:{},正确格式:{}",request.getDates(),"yyyy年MM月");
            return AjaxResult.error("日期校验失败");
        }catch (Exception e){
            logger.error("未知错误:{}",e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * <p>
     *     查询APP左上角的日期数据
     * </p>
     * @return 日期的集合
     */
//    @Anonymous
    @GetMapping("/getUniqueDatesFromDatabase")
    public AjaxResult getUniqueDatesFromDatabase(){
        List<String> dateArgs = bizFocusSchedulingProductProductionService.getUniqueDatesFromDatabase();
        return AjaxResult.success(dateArgs);
    }


    @GetMapping("/selectChNodeByParentId")
    public AjaxResult selectChNodeByParentId(@RequestParam Map<String,String> params){
        if(StringUtils.isBlank(params.get("pId"))){
            return AjaxResult.warn("没有找到父级节点");
        }
        List<BizFocusSchedulingProductProduction> result = bizFocusSchedulingProductProductionService.selectChNodeByParentId(params.get("pId"));
        return AjaxResult.success(result);
    }

    /**
     * <p>
     *     将临时表中的数据迁移到正式表虽
     * </p>
     * @return
     */
//    @Anonymous
    @PostMapping("/transferDataInOneClick")
    public AjaxResult transferDataInOneClick(){
        return toAjax(bizFocusSchedulingProductProductionService.transferDataInOneClick());
    }

    /**
     * <p>
     *     清空所有的重点调度产品产量数据
     * </p>
     * @return
     */
    @DeleteMapping("/clearAllTableData")
    public AjaxResult clearAllTableData(){
        bizFocusSchedulingProductProductionService.clearAllTableData();
        return AjaxResult.success();
    }

    /**
     * <p>
     *     导入重点调度产品产量数据
     * </p>
     * @param params 前端传来的参数，目前只有一个月份
     * @param multipartFile 上传的Excel文件
     * @return 导入是否成功
     */
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestParam Map<String,String> params, @RequestPart("file") MultipartFile multipartFile){
        try{
            String yearMonth = params.get("yearMonth");
            if(StringUtils.isBlank(yearMonth)){
                return AjaxResult.warn("请选择导入的年月");
            }
            List<BizFocusSchedulingProductProduction> list = bizFocusSchedulingProductProductionService.selectBizFocusSchedulingProductProductionListNoParams();
            if(list != null && !list.isEmpty()){
                return AjaxResult.warn("导入前请先清空历史数据");
            }
            /* 上传文件的路径 */
            String absoluteExcelPath = fileUploadPath + File.separator + IdUtil.simpleUUID() + ".xlsx";
            File file = new File(absoluteExcelPath);
            if(!file.exists()){
                FileUtil.touch(file);
            }
            multipartFile.transferTo(file);
//            String uploadPath = FileUploadUtils.upload(AppConfig.getProfile(),multipartFile);
//            String absoluteExcelPath = FileUploadUtils.replaceAbsolutePath(uploadPath);
            return bizFocusSchedulingProductProductionService.importExcel(absoluteExcelPath,yearMonth);
        }catch (IOException e){
            return AjaxResult.error("导入失败");
        }
    }
}
